package org.an.proj.contacts.ui.side;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.an.ku.view.indexview.PinYinUtil;
import org.an.ku.view.indexview.PinyinComparator;
import org.an.proj.contacts.model.ContactInfo;
import org.an.proj.contacts.model.PhoneInfo;

/**
 * Created by fuchaoyang on 2017/11/21.<br/>
 * description：系统联系人备份到app
 */

public class SystemCopyHelper {
  private Context mContext;
  private List<ContactInfo> mContactInfos = new ArrayList<>();
  private QueryTask mTask;
  private Callback mCallback;

  public SystemCopyHelper(Context context, Callback callback) {
    mContext = context;
    mCallback = callback;
  }

  public static SystemCopyHelper newInstance(Context context, Callback callback) {
    return new SystemCopyHelper(context, callback);
  }

  /**
   * 开始查询
   */
  public void startQuery() {
    mTask = new QueryTask();
    mTask.execute();
  }

  /*
   * 自定义显示Contacts提供的联系人的方法
   */
  private void queryContacts() {
    ContentResolver contentResolver = mContext.getContentResolver();

    // 这里只查询指定的列
    String[] projection = {
      ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts._ID,
      ContactsContract.Contacts.HAS_PHONE_NUMBER, ContactsContract.Contacts.SORT_KEY_PRIMARY,
    };

    // Uri.parse("content://com.android.contacts/contacts"
    // 获得所有的联系人, 按照sort_key升序查询
    Cursor cursor =
      contentResolver.query(ContactsContract.Contacts.CONTENT_URI, projection, null, null, null);
    // 循环遍历
    if (cursor != null && cursor.moveToFirst()) {
      int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);
      int displayNameColumn = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);

      do {
        // 获得联系人的ID
        String contactId = cursor.getString(idColumn);
        // 获得联系人姓名
        String displayName = cursor.getString(displayNameColumn);
        if (displayName == null) displayName = "";
        ContactInfo contactInfo = new ContactInfo();
        contactInfo.setName(displayName);
        contactInfo.setPinyin(PinYinUtil.toPinyin(displayName));
        contactInfo.setJianpin(PinYinUtil.toJianPin(displayName));
        mContactInfos.add(contactInfo);

        // 查看联系人有多少个号码，如果没有号码，返回0
        int phoneCount =
          cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

        if (phoneCount > 0) {
          List<String> phones = new ArrayList<>();
          // 获得联系人的电话号码列表
          Cursor phoneCursor = mContext.
            getContentResolver()
            .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
              ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null);
          if (phoneCursor != null && phoneCursor.moveToFirst()) {
            do {
              //遍历所有的联系人下面所有的电话号码
              String phoneNumber = phoneCursor.getString(
                phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
              phones.add(phoneNumber);
            } while (phoneCursor.moveToNext());
          }
          // fixme 这个怎么处理呢，数据库中的这个字段只能通过get获取，get是通过访问PhoneInfoDao数据库获取的
          // 那么这里如何赋值呢
          if (phones.size() > 0) {
            contactInfo.mLocalPhones = new ArrayList<>();
            for (String phone : phones) {
              PhoneInfo phoneInfo = new PhoneInfo().getDefaultPhone();
              phoneInfo.setNum(phone);
              contactInfo.mLocalPhones.add(phoneInfo);
            }
          }
        }
      } while (cursor.moveToNext());
    }
  }

  public void cancel() {
    if (mTask != null) mTask.cancel(true);
  }

  private class QueryTask extends AsyncTask<Void, Void, Void> {

    @Override protected Void doInBackground(Void... params) {
      ((Activity) mContext).runOnUiThread(new Runnable() {
        @Override public void run() {
          mCallback.onQueryStart();
        }
      });
      queryContacts();
      Collections.sort(mContactInfos, new PinyinComparator<ContactInfo>() {
        @Override public int compare(ContactInfo s1, ContactInfo s2) {
          return compare(s1.getName(), s2.getName());
        }
      });
      return null;
    }

    @Override protected void onPostExecute(Void aVoid) {
      ((Activity) mContext).runOnUiThread(new Runnable() {
        @Override public void run() {
          mCallback.onQueryEnd(mContactInfos);
        }
      });

      /*if (mContactInfos != null && mContactInfos.size() > 0) {
        ContactInfoDao mContactDao = DBManager.getDaoSession().getContactInfoDao();
        PhoneInfoDao mPhoneDao = DBManager.getDaoSession().getPhoneInfoDao();
        mContactDao.insertInTx(mContactInfos);
        mPhoneDao.insertInTx();
      }*/
    }
  }

  public interface Callback {
    void onQueryStart();

    void onQueryEnd(List<ContactInfo> list);
  }
}
